package org.NooLab.glue.net.http.rest.resources;

import org.NooLab.glue.net.http.rest.RestletBoxPropertiesIntf;
import org.NooLab.glue.net.http.rest.RestletMessageSinkIntf;
import org.NooLab.utilities.logging.PrintLog;
import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.data.ChallengeScheme;
import org.restlet.routing.Router;
import org.restlet.routing.Template;
import org.restlet.security.ChallengeAuthenticator;
import org.restlet.security.MapVerifier;




abstract public class ResourceBindingForClients extends Application{
	
	protected RestletMessageSinkIntf messageSink ;
	
	String role = "" ;
	
	String glueDefaultUser="", glueDefaultUsersPwd="";
	
	protected boolean useAuthentication = true;
	PrintLog out = new PrintLog(4,true) ;
	
	
	public ResourceBindingForClients( RestletBoxPropertiesIntf restletBoxProperties ){
		glueDefaultUser = restletBoxProperties.getBoxUserName() ;
    	glueDefaultUsersPwd = restletBoxProperties.getBoxUserPwd() ;
	}
	
	
    /**
     * Creates a root Restlet that will receive all incoming calls.
     */
    @Override
    abstract public Restlet createInboundRoot( ) ; 
	 
    
    protected ChallengeAuthenticator introduceAuthenticator( Router router ){
    	
    	ChallengeAuthenticator guard ;
    	MapVerifier verifier ;

        // Create a simple password verifier
        verifier = new MapVerifier();
        verifier.getLocalSecrets().put( glueDefaultUser, glueDefaultUsersPwd.toCharArray());

        // Create a Guard
        // Attach a guard to secure access to the directory
        guard = new ChallengeAuthenticator( router.getContext(),ChallengeScheme.HTTP_BASIC, "NooLabGlue");
        guard.setVerifier(verifier);
        router.attach("/", guard).setMatchingMode( Template.MODE_STARTS_WITH);// MODE_EQUALS

        
        guard.setNext( router ) ; // DataResource.class
        // That's the trick !!! not putting a special class as next, but the router itself,
        // then 404 (not found for incorrect path) and 401 (unauthorized) work together !
        // should be in the tutorial ...
        
    	return guard;
    }


	public RestletMessageSinkIntf getMessageSink() {
		return messageSink;
	}

	
    
}

